$(function() {
	init();
});

var dataArr = null;

function init() {
	var jsonParam = {};
	jsonParam.quoName = "";
	jsonParam.status = "";
	jsonParam.updateDateFrom = "";
	jsonParam.updateDateTo = "";
	jsonParam.sortField = "";
	jsonParam.sortDir = "";
	padMarketing.ajaxNormal('/pad_marketing/main/getQuoByName.action',jsonParam,
		function(data){
			dataArr = data;
			showData();
		},
		function(data){
			alert('失败');
		},
		true, true, "系统正在查询您名下建议书，请耐心等待"
	);
}

function showData() {
	data = dataArr;
	dataArr = [];
	var letterList = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N",
	                    "O","P","Q","R","S","T","U","V","W","X","Y","Z","#"];
	var statusList = ["P", "C", "F"];
	var proposalList = [];
	var tpl_proposal_list = $("#tpl_proposal_list").html();
	var tpl_proposal = $("#tpl_proposal").html();
	var tpl_proposal_check = $("#tpl_proposal_check").html();
	var tpl_proposal_update = $("#tpl_proposal_update").html();
	var tpl_proposal_delete = $("#tpl_proposal_delete").html();
	var tpl_proposal_read = $("#tpl_proposal_read").html();
	var tpl_proposal_pay = document.getElementById("tpl_proposal_pay").innerHTML;
	var tpl_proposal_send = $("#tpl_proposal_send").html();
	var proposal_list = [];
	var link_list = [];
	for(var i = 0; i < letterList.length; i++) {
		if(!proposalList[letterList[i]]) {
			proposalList[letterList[i]] = [];
		}
		for(var j = 0; j < statusList.length; j++) {
			if(!proposalList[letterList[i]][statusList[j]]) {
				proposalList[letterList[i]][statusList[j]] = [];
			}
		}
		proposalList[letterList[i]].size = 0;
	}
//	console.log(proposalList);
	for(var i = 0; i < data.length; i++) {
		var proposal = data[i];
		proposalList[proposal.headLetter][proposal.status].push(proposal);
		proposalList[proposal.headLetter].size++;
	}
	
	for(letter in proposalList) {
		if(proposalList[letter].size == 0) continue;
		var proposal_lis = [];
		var proposalStatus = proposalList[letter];
//		console.log(proposalStatus);
		for(status in proposalStatus) {
			if(status == "size" || proposalStatus[status].length == 0) continue;
			var proposals = proposalStatus[status];
			for(var i = 0; i < proposals.length; i++) {
				var proposal = proposals[i];
				dataArr.push(proposal);
				var id = dataArr.length - 1;
				var status = "<label class='sort sort-success'><i>完成</i></label>";
				var proposal_check = "";
				var proposal_update = "";
				var proposal_delete = "";
				var proposal_read = "";
				var proposal_pay = "";
				var proposal_send = "";
				var proposal_img = "/pad_marketing/html/img/login-bg.jpg";
				if(proposal.status == "F") {
					proposal_pay = tpl_proposal_pay.replace(/\{proposalIndex\}/g, id);
					proposal_read = tpl_proposal_read.replace(/\{proposalIndex\}/g, id);
				} else {
					proposal_check = tpl_proposal_check.replace(/\{proposal\}/g, "data-proposal='" + JSON.stringify(proposal) + "'");
					proposal_update = tpl_proposal_update.replace(/\{proposalIndex\}/g, id);
					proposal_delete = tpl_proposal_delete.replace(/\{proposalIndex\}/g, id);
				}
				if(proposal.status == "P") {
					status = "<label class='sort sort-warning'><i>暂存</i></label>";
				} else if(proposal.status == "C") {
					proposal_pay = tpl_proposal_pay.replace(/\{proposalIndex\}/g, id);
					proposal_send = tpl_proposal_send.replace(/\{proposalIndex\}/g, id);
					status = "<label class='sort sort-primary'><i>已初核</i></label>";
				}
//				console.log(JSON.stringify(proposal));
				if(proposal.faceImg != "") {
					proposal_img = proposal.faceImg;
				}
				var proposal_html = tpl_proposal.replace(/\{status\}/g, status)
												.replace(/\{quoName\}/g, HtmlEncode(proposal.quoName))
												.replace(/\{proposal-update\}/g, proposal_update)
												.replace(/\{proposal-check\}/g, proposal_check)
												.replace(/\{proposal-delete\}/g, proposal_delete)
												.replace(/\{proposal-read\}/g, proposal_read)
												.replace(/\{proposal-img\}/g, proposal_img)
												.replace(/\{proposal-pay\}/g, proposal_pay)
												.replace(/\{proposal-send\}/g, proposal_send)
												.replace(/\{proposalIndex\}/g, id);
//				console.log(proposal_html);
				proposal_lis.push(proposal_html);
			}
		}
		
		var proposal_ul = tpl_proposal_list.replace(/\{proposal-list\}/g, proposal_lis.join(''))
										   .replace(/\{lowercase\}/g, letter.toLowerCase())
										   .replace(/\{uppercase\}/g, letter);
		link_list.push("<a href='#" + letter.toLowerCase() + "'>" + letter + "</a>");
		proposal_list.push(proposal_ul);
	}
//	console.log(proposal_list.join(''));
	$("#proposal-list").html(proposal_list.join(''));
	$(".a-z").html(link_list.join(''));
	$(".bookshelf").popover();
	$(".bookshelf-list").popover();
	if(myScroll2) {
		myScroll2.refresh();
	}
}
//点击查看,与修改一致，只在url后带view=true
function viewProposal(index){
	if(dataArr&&dataArr[index]){
		sessionStorage.returnUrl = '/pad_marketing/plan/proposalMangeName.action';
		sessionStorage.quoBase = JSON.stringify(dataArr[index]);
		location.href = '/pad_marketing/plan/proposalNew.action?view=true';
	}else {
		console.log('数据异常'+index);
	}
}
//点击修改
function modProposal(index){
	if(dataArr&&dataArr[index]){
		sessionStorage.returnUrl = '/pad_marketing/plan/proposalMangeName.action';
		sessionStorage.quoBase = JSON.stringify(dataArr[index]);
		location.href = '/pad_marketing/plan/proposalNew.action';
	}else {
		console.log('数据异常'+index);
	}
		
}

function deleteProposals() {
	var proposals = [];
	$("input[name='proposal']:checked").each(function() {
		proposals.push(dataArr[$(this).val()]);
	});
	if(proposals.length == 0) {
		alertMsg("请至少选择一项删除");
		return ;
	}
	console.log(proposals);
	alertMsg("确定要删除所选建议书?", 1, function() {
		padMarketing.ajaxNormal('/pad_marketing/main/quoDelete.action', proposals,
			function(data){
				console.log(data);
				$("input[name='proposal']:checked").each(function() {
					$(this).closest('dl').remove();
				});
				$(".icon-return").click();
				if(myScroll2) {
					myScroll2.refresh();
				}
			},
			function(data){
				alert('失败');
			}
		);
	});
}

function delteOne(id, target) {
	var proposals = [];
	proposals.push(dataArr[id]);
//	console.log($(target).parent().parent().parent().html());
	alertMsg("确定要删除该建议书?", 1, function() {
//		console.log(proposals);
		padMarketing.ajaxNormal('/pad_marketing/main/quoDelete.action', proposals,
			function(data){
				console.log('success');
				$(target).closest('dl').remove();
				if(myScroll2) {
					myScroll2.refresh();
				}
			},
			function(data){
				alert('失败');
			}
		);
	});
}

function proposalCopy(id) {
	if(!dataArr || !dataArr[id]) {
		console.log("数据有误");
		return ;
	}
	var jsonParam = {};
	jsonParam.quoId = dataArr[id].quoId;
	jsonParam.sign = dataArr[id].sign;
	console.log(dataArr);
	padMarketing.ajaxNormal('/pad_marketing/main/quoCopy.action', jsonParam,
		function(data){
			console.log('success');
			init();
		},
		function(data){
			alert('失败');
		}
	);
}

function reset() {
	$("#quoName").val('');
	$("#phName").val('');
	$("#updateDateFrom").val('');
	$("#updateDateTo").val('');
	$("#status").val('');
}

function dateCheck() {
	var updateDateFrom = $("#updateDateFrom").val();
	var updateDateTo = $("#updateDateTo").val();
	if(updateDateFrom && updateDateTo && updateDateFrom > updateDateTo) {
		alertMsg('起止日期不能大于结束日期');
		$("#updateDateFrom").val('');
		$("#updateDateTo").val('');
	}
}

function quoSearch() {
	var jsonParam = {};
	jsonParam.quoId = "";
	jsonParam.quoName = $("#quoName").val();
	jsonParam.phName = $("#phName").val();
	jsonParam.status = $("#status").val();
	jsonParam.updateDateFrom = $("#updateDateFrom").val();
	jsonParam.updateDateTo = $("#updateDateTo").val();
	jsonParam.sortField = "";
	jsonParam.sortDir = "";
	padMarketing.ajaxNormal('/pad_marketing/main/getQuoByName.action', jsonParam,
		function(data){
			dataArr = data;
//			console.log(dataArr);
			closeDiv('open1');
			reset();
			showData();
		},
		function(data){
			alertMsg('查询失败请重试');
		},
		true, true, "系统正在查询您名下建议书，请耐心等待"
	);
}

function payProposal(index) {
	var quoBase = dataArr[index];
	padMarketing.ajaxNormal('/pad_marketing/main/quoToApps.action', quoBase,
		function(data) {
			var appBases = data;
			sessionStorage.returnUrl = '/pad_marketing/plan/proposalMangeName.action';
			if(appBases.length == 1) {
				sessionStorage.appBase = JSON.stringify(appBases[0]);
				window.location.href = "/pad_marketing/purchaseNote/index.action";
			}else{
				$('#change').remove();
				var p = '<div class="open-body font-16"  id="change"  ><p  class="add font-12 gray">请点选其中的一张订单继续投保操作，剩余订单请在订单书架中查找</p></div>';
				$('#open6 h4').after(p);
				for (var i = 0; i < appBases.length; i++) {

					var add_risk = '<div class="show"><div class="blank-1"></div><div class="form-group"><div class="col-md-4"><p class="p-overflow" title="">'
							+ appBases[i].productName
							+ '</p></div><div class="col-md-6 text-right"><p class="p-overflow">订单号：<span class="orange">'
							+ appBases[i].orderId
							+ '</span></p> </div><div class="col-md-2 text-right"><div  class="radio_blo"><input id="input'
							+ i
							+ '" data="'
							+ appBases[i]
							+ '" type="radio" name="xx" /><label for="input'
							+ i
							+ '">&nbsp;</label></div></div></div><hr></div>';
					$('.add').append(add_risk);
				}

				$(".radio_blo input").click(function() {
					sessionStorage.removeItem('appBase');
					var ind = $("input[name=xx]:checked").closest('.show').index();
					if(ind!=-1){
						$('#text-center').off().on('click',function(){
							sessionStorage.appBase = JSON.stringify(appBases[ind]);
							window.location.href = "/pad_marketing/purchaseNote/index.action";	
						});
					}
					
				});
				showDiv('open6');
			}
		},
		function(data) {
			alertMsg(data.responseText);
			console.log('失败');
		}
	);
}

function toProposal(index) {
	var proposal = dataArr[index];
	sessionStorage.returnUrl = '/pad_marketing/plan/proposalMangeName.action';
	sessionStorage.quoBase = JSON.stringify(dataArr[index]);
	window.location.href = "/pad_marketing/plan/proposal.action?quoId=" + proposal.quoId + "&sign=" + proposal.sign;
}